package com.kfm.jdbc.day0327;

import java.sql.*;

public class Demo02 {

    public static void main(String[] args) {
        try {
            // 1. 注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2. 获取连接
            String url = "jdbc:mysql://localhost:3306/kfm_store";
            String username = "root";
            String password = "";
            Connection connection = DriverManager.getConnection(url, username, password);

            // 3. 预处理 SQL
            String sql ="insert into account (phone, password, type, name) values(?, ?, ?, ?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

            // 4. 设置值
            preparedStatement.setObject(1, "888");
            preparedStatement.setObject(2, "123456");
            preparedStatement.setObject(3, 0);
            preparedStatement.setObject(4, "test7");

            // 5. 执行 SQL
            int row = preparedStatement.executeUpdate();

            // 6. 处理结果集
            System.out.println(row);

            ResultSet resultSet = preparedStatement.getGeneratedKeys();
            resultSet.next();
            System.out.println(resultSet.getObject(1));

            // 7. 释放资源
            preparedStatement.close();
            connection.close();

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
